package com.ld.action;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationAction;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.ld.explanation.TextExplanation;
import org.jetbrains.annotations.NotNull;

public class Translate extends AnAction {

    public Translate(){

    }
    @Override
    public void update(@NotNull AnActionEvent e) {
        super.update(e);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext());
        if (editor != null){
            String selectedText = editor.getSelectionModel().getSelectedText();
            int selectionStart = editor.getSelectionModel().getSelectionStart();
            int selectionEnd = editor.getSelectionModel().getSelectionEnd();
            if (selectedText != null && selectedText != ""){
                String translation = TextExplanation.getTextExplanation(editor).translation();
                if (editor.getDocument().isWritable()){
                    WriteCommandAction.runWriteCommandAction(editor.getProject(),()->{
                        editor.getDocument().replaceString(selectionStart,selectionEnd,translation);
                    });
                }else {
                    Notification notification = new Notification(
                            "",
                            "probie translate",
                            translation,
                            NotificationType.INFORMATION);
                    Notifications.Bus.notify(notification);
                }
            }
        }
    }
}